<template>
  <div class="app-container">
    <el-container>
      <!--   搜索栏begin   -->
      <el-header>
        <el-form :inline="true" class="demo-form-inline">
          <el-form-item label="资源名称">
            <el-input v-model="queryParams.name" placeholder="请输入资源名称" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" @click="fetchResourceList">查询</el-button>
          </el-form-item>
        </el-form>
      </el-header>
      <!--   搜索栏end   -->

      <el-container>
        <!--   侧边栏 树形目录begin   -->
        <el-aside :width="isAsideCollapsed?'0':'18%'">
          <el-tree
            ref="tree2"
            :data="resourceTree"
            :props="defaultProps"
            :filter-node-method="filterNode"
            class="filter-tree"
            style="margin: 10px;"
          />
        </el-aside>
        <!--   侧边栏 树形目录end   -->

        <!--   主页面 列表begin   -->
        <el-main>
          <el-row>
            <el-button
              icon="el-icon-arrow-right"
              circle
              class="toggleAsideBtn"
              :class="{'is-active':!isAsideCollapsed}"
              @click="toggleAside"
            />
            <el-button type="primary" icon="el-icon-plus" @click="openAddDialog">增加</el-button>
            <el-button type="primary" icon="el-icon-copy-document" @click="copyResources">复制</el-button>
            <template>
              <el-popconfirm
                confirm-button-text="好的"
                cancel-button-text="不用了"
                icon="el-icon-info"
                icon-color="red"
                title="确定删除这些资源吗？"
                @onConfirm="deleteResources(multipleSelectionId)"
              >
                <el-button slot="reference" type="danger" icon="el-icon-delete" style="margin-left: 10px;" :disabled="multipleSelectionId.length===0">删除</el-button>
              </el-popconfirm>
            </template>
            <el-button type="primary" icon="el-icon-refresh" style="margin-left: 10px;" @click="fetchResourceList">刷新</el-button>
            <el-button icon="el-icon-menu" circle style="position: absolute; right: 0;" @click="colDialogVisible = true" />
          </el-row>

          <el-table :data="resourceList" style="width: 100%" row-key="id" :reserve-selection="true" @selection-change="handleSelectionChange">
            <el-table-column
              type="selection"
              width="55"
            />
            <el-table-column type="expand">
              <template slot-scope="props">
                <el-form label-position="left" inline class="demo-table-expand" label-width="100px">
                  <el-form-item label="资源名称">
                    <span>{{ props.row.name }}</span>
                  </el-form-item>
                  <el-form-item label="父亲节点">
                    <span>{{ props.row.parentName }}</span>
                  </el-form-item>
                  <el-form-item label="子系统">
                    <span>{{ props.row.subSystemName }}</span>
                  </el-form-item>
                  <el-form-item label="URL">
                    <span>{{ props.row.url }}</span>
                  </el-form-item>
                  <el-form-item label="API">
                    <span>{{ props.row.api }}</span>
                  </el-form-item>
                  <el-form-item label="资源类型">
                    <span>{{ formatResourceType(props.row) }}</span>
                  </el-form-item>
                  <el-form-item label="打开图标">
                    <span>{{ props.row.openImg }}</span>
                  </el-form-item>
                  <el-form-item label="关闭图标">
                    <span>{{ props.row.closeImg }}</span>
                  </el-form-item>
                  <el-form-item label="不可见">
                    <span>{{ formatStatus(props.row) }}</span>
                  </el-form-item>
                </el-form>
              </template>
            </el-table-column>
            <el-table-column
              label="序号"
              type="index"
              width="50"
            />
            <el-table-column label="资源名称" prop="name" />
            <!-- 根据选择情况显示的列 -->
            <!--   parentName:父亲节点 subSystemName:子系统 url:URL api:API resourceType:资源类型 openImg:打开图标 closeImg:关闭图标 status:不可见   -->
            <el-table-column v-if="columnsVisibility.parentName" label="父亲节点" prop="parentName" />
            <el-table-column v-if="columnsVisibility.subSystemName" label="子系统" prop="subSystemName" />
            <el-table-column v-if="columnsVisibility.url" label="URL" prop="url" />
            <el-table-column v-if="columnsVisibility.api" label="API" prop="api" />
            <el-table-column v-if="columnsVisibility.resourceType" label="资源类型" prop="resourceType" :formatter="formatResourceType" />
            <el-table-column v-if="columnsVisibility.openImg" label="打开图标" prop="openImg" />
            <el-table-column v-if="columnsVisibility.closeImg" label="关闭图标" prop="closeImg" />
            <el-table-column v-if="columnsVisibility.status" label="不可见" prop="status" :formatter="formatStatus" />
            <el-table-column align="center" label="操作" width="250">
              <template slot-scope="scope">
                <el-row>
                  <el-button type="primary" @click="copyResource(scope.row)">复制</el-button>
                  <el-button @click="openEditDialog(scope.row)">编辑</el-button>
                  <template>
                    <el-popconfirm
                      confirm-button-text="好的"
                      cancel-button-text="不用了"
                      icon="el-icon-info"
                      icon-color="red"
                      title="确定删除这个资源吗？"
                      @onConfirm="deleteResource(scope.row.id)"
                    >
                      <el-button slot="reference" type="danger" style="margin-left: 10px;">删除</el-button>
                    </el-popconfirm>
                  </template>
                </el-row>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            :page-size="10"
            layout="total, sizes, prev, pager, next, jumper"
            :page-sizes="[10, 20, 30, 40]"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />

          <!--     选择列弹窗begin     -->
          <el-dialog title="选择列" :visible.sync="colDialogVisible" width="30%" :before-close="handleClose">
            <el-checkbox v-model="checkAll" :indeterminate="isIndeterminate" @change="handleCheckAllChange">全选</el-checkbox>
            <div style="margin: 15px 0;" />
            <el-checkbox-group v-model="checkedColumns" @change="handleCheckedColumnsChange">
              <el-checkbox v-for="column in columnOptions" :key="column" :label="column">{{ columnLabels[column] }}</el-checkbox>
            </el-checkbox-group>
            <span slot="footer" class="dialog-footer">
              <el-button @click="colDialogVisible = false">取 消</el-button>
              <el-button type="primary" @click="closeColDialog">确 定</el-button>
            </span>
          </el-dialog>
          <!--     选择列弹窗end     -->

          <!--     资源弹窗begin     -->
          <ResourceDialog
            :dialog-flag.sync="showDialog"
            :dialog-type="dialogType"
            :resource="dialogResource"
          />
          <!--     资源弹窗end     -->
        </el-main>
        <!--   主页面 列表end   -->
      </el-container>
    </el-container>

  </div>
</template>

<script>
import {
  deleteResourceById,
  deleteResourceByIdList,
  getResourceList,
  getTreeResource,
  insertResource
} from '@/api/resource'
import ResourceDialog from './ResourceDialog.vue'

export default {
  name: 'Resource',
  components: {
    ResourceDialog
  },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'gray',
        deleted: 'danger'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      // 侧边栏显示
      isAsideCollapsed: true,
      // 树形目录
      resourceTree: [],
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      // ---------- 列表begin ----------
      // 列表分页
      total: 3,
      queryParams: {
        name: '', // 模糊查询名称
        page: 1, // 当前页码
        pageSize: 10 // 每页显示的条目数
      },
      // 列表数据
      resourceList: [],
      multipleSelectionId: [],
      multipleSelection: [],
      // ---------- 列表end ----------
      // ---------- 列选择弹窗begin ----------
      colDialogVisible: false,
      checkAll: false,
      isIndeterminate: false,
      // 所有可选择的列
      columnOptions: [
        'parentName',
        'subSystemName',
        'url',
        'api',
        'resourceType',
        'openImg',
        'closeImg',
        'status'],
      // parentName:父亲节点 subSystemName:子系统 url:URL api:API resourceType:资源类型 openImg:打开图标 closeImg:关闭图标 status:不可见
      // 列对应的标签名称
      columnLabels: {
        parentName: '父亲节点',
        subSystemName: '子系统',
        url: 'URL',
        api: 'API',
        resourceType: '资源类型',
        openImg: '打开图标',
        closeImg: '关闭图标',
        status: '不可见'
      },
      // 默认选中的列
      checkedColumns: [
        'parentName',
        'subSystemName',
        'api',
        'resourceType',
        'openImg',
        'closeImg'
      ],
      columnsVisibility: {
        parentName: true,
        subSystemName: true,
        url: false,
        api: true,
        resourceType: true,
        openImg: true,
        closeImg: true,
        status: false
      },
      // ---------- 列选择弹窗end ----------
      // ---------- 列表资源弹窗begin ----------
      showDialog: false,
      dialogType: 0, // 0-增加 1-编辑
      dialogResource: {}
      // ---------- 列表资源弹窗end ----------
    }
  },
  watch: {
    filterText(val) {
      this.$refs.tree2.filter(val)
    }
  },
  created() {
    this.fetchResourceTree()
    this.fetchResourceList()
  },
  methods: {
    // 树形目录
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    fetchResourceTree() {
      getTreeResource(this.queryParams).then(response => {
        this.resourceTree = response.data
      }).catch(() => {})
    },
    // 侧边栏收缩
    toggleAside() {
      this.isAsideCollapsed = !this.isAsideCollapsed
    },
    // ---------- 选择列弹窗begin ----------
    handleCheckAllChange(val) {
      this.checkedColumns = val ? this.columnOptions : []
      this.isIndeterminate = false
    },
    handleCheckedColumnsChange(value) {
      const checkedCount = value.length
      this.checkAll = checkedCount === this.columnOptions.length
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.columnOptions.length
    },
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done()
        })
        .catch(_ => {})
    },
    closeColDialog() {
      this.colDialogVisible = false
      this.columnOptions.forEach(column => {
        this.columnsVisibility[column] = this.checkedColumns.includes(column)
      })
    },
    // ---------- 选择列弹窗end ----------
    // ---------- 分页begin ----------
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
      this.queryParams.pageSize = val
      this.fetchResourceList()
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`)
      this.queryParams.page = val
      this.fetchResourceList()
    },
    fetchResourceList() {
      getResourceList(this.queryParams).then(response => {
        this.resourceList = response.data.records
        this.total = response.data.total
      }).catch(() => {})
    },
    // ---------- 分页end ----------
    // ---------- 资源弹窗begin ----------
    openAddDialog() {
      console.log('打开增加资源弹窗')
      this.dialogType = 0
      this.dialogResource = undefined
      this.showDialog = true
    },
    openEditDialog(row) {
      console.log('打开编辑资源弹窗')
      this.dialogType = 1
      this.dialogResource = row
      this.showDialog = true
    },
    // ---------- 资源弹窗end ----------
    // ---------- 列表begin ----------
    formatResourceType(row) {
      return row.resourceType === 0 ? '菜单' : row.resourceType === 1 ? '按钮' : '未填写'
    },
    formatStatus(row) {
      return row.status === 0 ? '不可见' : row.status === 1 ? '可见' : '未填写'
    },
    // 多选
    handleSelectionChange(val) {
      this.multipleSelection = val
      this.multipleSelectionId = val.map(row => row.id)
    },
    // 根据ID删除资源
    deleteResource(id) {
      deleteResourceById(id).then(() => {
        // 处理成功删除后的逻辑，比如刷新列表
        this.fetchResourceList()
        this.$message({
          message: '删除资源成功',
          type: 'success'
        })
      }).catch(() => {
        // 处理删除失败的逻辑
        this.$message.error('删除资源时出错')
      })
    },
    // 批量删除资源
    deleteResources(idList) {
      deleteResourceByIdList(idList).then(() => {
        // 处理成功删除后的逻辑，比如刷新列表
        this.fetchResourceList()
        this.$message({
          message: '删除资源成功',
          type: 'success'
        })
      }).catch(() => {
        // 处理删除失败的逻辑
        this.$message.error('删除资源时出错')
      })
    },
    // 复制资源
    copyResource(resource) {
      insertResource(resource)
        .then(response => {
          this.fetchResourceList()
          console.log('复制资源成功:', response)
          this.$message({
            message: '复制资源成功',
            type: 'success'
          })
        })
        .catch(error => {
          console.error('复制资源时出错:', error)
          this.$message.error('复制资源时出错')
        })
    },
    // 批量复制资源
    copyResources() {
      this.multipleSelection.forEach(resource => {
        this.copyResource(resource)
      })
    }
    // ---------- 列表end ----------
  }
}
</script>

<style scoped>
/* 页面布局begin */
.el-header {
  //text-align: center;
  padding: 10px;
}

.el-aside {
  text-align: center;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.el-main {
  //text-align: center;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}
/* 页面布局end */

/* 侧边栏收缩按钮旋转 */
.toggleAsideBtn.is-active {
  transform: rotate(180deg);
}

/* 列表 */
.el-table {
  margin-top: 20px;
  margin-bottom: 20px;
}

/* 列表展开start */
.demo-table-expand {
  font-size: 0;
}
.demo-table-expand label {
  width: 90px;
  color: #99a9bf;
}
.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 50%;
}
/* 列表展开end */
</style>
